package com.mj.postcode.activity;

import java.util.ArrayList;
import java.util.List;

import com.SYY.cbsdk.ui.AppControl;
import com.dyk.hfsdk.dao.util.DevListener;
import com.dyk.hfsdk.ui.Access;
import com.mj.postcode.R;
import com.mj.postcode.bean.Postcode;
import com.mj.postcode.service.PostcodeService;
import com.mj.postcode.util.NetUtils;
import com.mj.postcode.widget.LoadingDialog;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;

/**
 * 地址查邮编
 * @author zhaominglei
 * @date 2015-11-10
 * 
 */
public class TocodeActivity extends Activity implements OnClickListener,DevListener {
	@SuppressWarnings("unused")
	private static final String TAG = TocodeActivity.class.getSimpleName();
	private PostcodeService postcodeService = new PostcodeService();
	private ImageView goHome;
	private ArrayAdapter<String> provinceAdapter;
	private Spinner provinceSpinner; //省份/直辖市
	private String province; //省份/直辖市
	private ArrayAdapter<String> cityAdapter;
	private Spinner citySpinner; //市
	private String city; //市
	private ArrayAdapter<String> districtAdapter;
	private Spinner districtSpinner; //区、县
	private String district; //区、县
	private EditText addressEdt; //地址
	private String address; //地址
	private Button queryBtn; //查询
	private ProgressBar queryProgressBar; //查询进度条
	private TextView resultView; //结果	
	private Button appOffersButton; //推荐应用
	private LoadingDialog loadingDialog; //加载框
	private LinearLayout miniAdLinearLayout; //迷你广告
    private AppControl appControl;
    private Access access;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_tocode);
		init();
	}
	
	private void init() {
		goHome = (ImageView)findViewById(R.id.tocode_gohome);		
		provinceSpinner = (Spinner)findViewById(R.id.tocode_province_spinner);
		citySpinner = (Spinner)findViewById(R.id.tocode_city_spinner);
		districtSpinner = (Spinner)findViewById(R.id.tocode_district_spinner);
		addressEdt = (EditText)findViewById(R.id.tocode_address_edt);
		queryBtn = (Button)findViewById(R.id.tocode_query_btn);
		queryProgressBar = (ProgressBar)findViewById(R.id.tocode_query_progressbar);
		resultView = (TextView)findViewById(R.id.tocode_result);
		appOffersButton = (Button)findViewById(R.id.tocode_appOffersButton);
		miniAdLinearLayout = (LinearLayout)findViewById(R.id.tocode_miniAdLinearLayout);
		
		goHome.setOnClickListener(this);
		queryBtn.setOnClickListener(this);
		appOffersButton.setOnClickListener(this);
		loadingDialog = new LoadingDialog(this);
		loadingDialog.show();
		List<String> provinces = postcodeService.getProvinces(this);
		provinceAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, provinces);
		provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		provinceSpinner.setAdapter(provinceAdapter);
		cityAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new ArrayList<String>());
		cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		citySpinner.setAdapter(cityAdapter);
		districtAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new ArrayList<String>());
		districtAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		districtSpinner.setAdapter(districtAdapter);
		if (provinces != null && !provinces.isEmpty()) {
			String province = provinces.get(0);
			List<String> cities = postcodeService.getCities(this, province);
			if (cities != null && !cities.isEmpty()) {
				for (String city : cities) {
					cityAdapter.add(city);
				}
				cityAdapter.notifyDataSetChanged();
				String city = cities.get(0);
				List<String> districts = postcodeService.getDistricts(this, province, city);
				if (districts != null && !districts.isEmpty()) {
					for (String district : districts) {
						districtAdapter.add(district);
					}
					districtAdapter.notifyDataSetChanged();
				}
			}
		}
		loadingDialog.dismiss();
		provinceSpinner.setOnItemSelectedListener(new ProvinceSelectedListener());
		citySpinner.setOnItemSelectedListener(new CitySelectedListener());
		
    	appControl = AppControl.getInstance();
		appControl.init(TocodeActivity.this, MainActivity.MUMAYI_APPID, MainActivity.MUMAYI_APPCHANNEL);
		appControl.loadPopAd(TocodeActivity.this);
		appControl.showPopAd(TocodeActivity.this, 60 * 1000);
		appControl.showInter(TocodeActivity.this, miniAdLinearLayout);
		
		access = Access.getInstance();
		// 初始化带player_id
		access.init(TocodeActivity.this, MainActivity.MUMAYI_APPID, MainActivity.MUMAYI_APPCHANNEL);
		// 设置初始积分                                                              
		access.setdefaultSCORE(this, 100);
		// 设置获取积分的监听
		access.setAppListener(this, this);			
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tocode_gohome:
			TocodeActivity.this.finish();
			break;
		
		case R.id.tocode_query_btn:
			province = provinceSpinner.getSelectedItem().toString();
			if (province == null || province.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.tocode_province_prompt, Toast.LENGTH_SHORT).show();
				return;
			}
			city = citySpinner.getSelectedItem().toString();
			if (city == null || city.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.tocode_city_prompt, Toast.LENGTH_SHORT).show();
				return;
			}
			district = districtSpinner.getSelectedItem().toString();
			if (district == null || district.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.tocode_district_prompt, Toast.LENGTH_SHORT).show();
				return;
			}
			address = addressEdt.getText().toString();
			resultView.setText("");
			getCodeInfo();
			break;
			
		case R.id.tocode_appOffersButton:
			break;
		
		default:
			break;
		}
	}

	private void getCodeInfo() {
		if (NetUtils.isConnected(getApplicationContext())) {
			queryProgressBar.setVisibility(View.VISIBLE);
			new CodeInfoAsyncTask().execute("");
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onBackPressed() {
		TocodeActivity.this.finish();
	}
	
	/**
	 * 省选择监听器
	 */
	public class ProvinceSelectedListener implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			String province = ((TextView)view).getText().toString();
			if (province != null && !province.equals("")) {
				cityAdapter.clear();
				districtAdapter.clear();
				List<String> cities = postcodeService.getCities(getApplicationContext(), province);
				if (cities != null && !cities.isEmpty()) {
					for (String city : cities) {
						cityAdapter.add(city);
					}
					cityAdapter.notifyDataSetChanged();
					String city = cities.get(0);
					List<String> districts = postcodeService.getDistricts(getApplicationContext(), province, city);
					if (districts != null && !districts.isEmpty()) {
						for (String district : districts) {
							districtAdapter.add(district);
						}
						districtAdapter.notifyDataSetChanged();
					}
				}				
			}
		}
		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}
	}
	
	/**
	 * 市选择监听器
	 */
	public class CitySelectedListener implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			String province = provinceSpinner.getSelectedItem().toString();
			String city = ((TextView)view).getText().toString();
			if (province != null && !province.equals("") && city != null && !city.equals("")) {
				districtAdapter.clear();
				List<String> districts = postcodeService.getDistricts(getApplicationContext(), province, city);
				if (districts != null && !districts.isEmpty()) {
					for (String district : districts) {
						districtAdapter.add(district);
					}
					districtAdapter.notifyDataSetChanged();
				}
			}
		}
		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}
	}
	
	public class CodeInfoAsyncTask extends AsyncTask<String, String, List<Postcode>> {
		@Override
		protected List<Postcode> doInBackground(String... params) {
			return postcodeService.getCodeInfo(getApplicationContext(), null, province, city, district, address);
		}
		@Override
		protected void onPostExecute(List<Postcode> result) {
			queryProgressBar.setVisibility(View.GONE);
			if (result != null && !result.isEmpty()) {
				for (Postcode postcode : result) {
					List<Postcode> postcodes = postcode.getPostcodes();
					if (postcodes != null && !postcodes.isEmpty()) {
						StringBuilder sb = new StringBuilder();
						for (Postcode code : postcodes) {
							sb.append(code.getZipcode()).append(" ");
							sb.append(code.getProvince()).append(" ").append(code.getCity()).append(" ");
							sb.append(code.getDistrict()).append(" ").append(code.getAddress()).append(" \n\n");
						}
						resultView.setText(sb.toString());
					} 
				}
			} else {
				Toast.makeText(getApplicationContext(), R.string.tocode_error1, Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		appControl.close(this);
	}
	
	@Override
	public void onDevSucceed(int eggs) {
		System.out.println("积分获取成功:" + eggs);
	}

	@Override
	public void onDevFailed(String message) {
		System.out.println("积分获取失败:" + message);
	}

	@Override
	public void onClose(Context context) {
		((Activity) context).finish();
	}	
}
